package mws;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.LinkedBlockingQueue;

public class MapContext extends ServiceThread {

    private final MapperClient mapperClient;

    private LinkedBlockingQueue<Map<String, String>> queue;

    public MapContext(int port, String host) {
        this.mapperClient = new MapperClient(host, port);
        this.mapperClient.setMapContext(this);
        this.queue = new LinkedBlockingQueue<>();
        try {
            this.mapperClient.run();
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
    }

    private void writeSync(String key, String value) {
        mapperClient.sendSync(Map.of(key, value));
    }

    @Override
    public String getServiceName() {
        return MapContext.class.getName();
    }

    public void send(String key, String value) {
        try {
            log.info("send key: {}, value: {}", key, value);
            queue.put(new HashMap<>() {{
                put("key", key);
                put("value", value);
            }});
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
    }


    @Override
    public void run() {
        log.info("MapContext run");
        while (!isStopped()) {
            try {
                Map<String, String> data = queue.take();
                writeSync(data.get("key"), data.get("value"));

            } catch (InterruptedException e) {
                // 捕获中断异常后，需要重新设置中断标志（因为异常会清除标志）
                Thread.currentThread().interrupt();
                // 退出循环（因为中断通常意味着需要停止）
                break;
            }
        }
        log.info("MapContext stopped");
    }

    public void close() {
        stopped = true;
        // 中断工作线程（若线程在queue.take()处阻塞，会被唤醒并抛出异常）
        if (thread != null) {
            thread.interrupt();
        }
    }

}
